# -*- coding: utf-8 -*-
__author__ = 'sht'
__date__ = '2024-05-18 17:40'

import os
import threading
import wx
import wx.html2

class BrowserFrame(wx.Frame):
    def __init__(self, *args, **kw):
        super(BrowserFrame, self).__init__(*args, **kw)

        self.browser = wx.html2.WebView.New(self)

        self.url_bar = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
        self.url_bar.Bind(wx.EVT_TEXT_ENTER, self.on_enter_url)

        self.back_button = wx.Button(self, label="后退")
        self.back_button.Bind(wx.EVT_BUTTON, self.on_back)

        self.forward_button = wx.Button(self, label="前进")
        self.forward_button.Bind(wx.EVT_BUTTON, self.on_forward)

        nav_sizer = wx.BoxSizer(wx.HORIZONTAL)
        nav_sizer.Add(self.back_button, 0, wx.EXPAND | wx.ALL, 5)
        nav_sizer.Add(self.forward_button, 0, wx.EXPAND | wx.ALL, 5)
        nav_sizer.Add(self.url_bar, 1, wx.EXPAND | wx.ALL, 5)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(nav_sizer, 0, wx.EXPAND)
        sizer.Add(self.browser, 1, wx.EXPAND, 10)
        self.SetSizer(sizer)

        self.CreateStatusBar()
        self.SetStatusText("wxPython Browser")

        self.Bind(wx.EVT_CLOSE, self.on_close)

        # 绑定浏览器的加载完成事件，以便更新地址栏
        self.browser.Bind(wx.html2.EVT_WEBVIEW_NAVIGATED, self.on_page_loaded)

    def on_enter_url(self, event):
        url = self.url_bar.GetValue()
        if not url.startswith('http://') and not url.startswith('https://'):
            url = 'http://' + url
        self.browser.LoadURL(url)

    def on_back(self, event):
        if self.browser.CanGoBack():
            self.browser.GoBack()
            self.update_nav_buttons()

    def on_forward(self, event):
        if self.browser.CanGoForward():
            self.browser.GoForward()
            self.update_nav_buttons()

    def on_page_loaded(self, event):
        self.url_bar.SetValue(self.browser.GetCurrentURL())
        self.update_nav_buttons()

    def update_nav_buttons(self):
        self.back_button.Enable(self.browser.CanGoBack())
        self.forward_button.Enable(self.browser.CanGoForward())

    def on_close(self, event):
        self.browser.Destroy()
        self.Destroy()


class MyApp(wx.App):
    def OnInit(self):
        self.frame = BrowserFrame(None, title="wxPython Browser", size=(800, 600))
        self.frame.Show()
        return True

def main():
    app = MyApp()
    # app.frame.browser.LoadURL("http://127.0.0.1:8089")
    app.frame.browser.LoadURL("https://g22z.com")
    app.MainLoop()


def start():
    # 不知道为什么这里在子线程启动会崩溃，但实际django项目里试过启动django的时候在子线程启动窗口，很奇怪。
    # try:
    #     thread = threading.Thread(target=main, args=())
    #     thread.start()
    # except KeyboardInterrupt:
    #     os._exit(1)
    main()
